import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/router/page_router.dart';
import 'package:yqmssa_app/utils/shared_utils.dart';
import 'package:yqmssa_app/widget/disagree_dialog_widget.dart';
import 'package:yqmssa_app/widget/xie_yi_widget.dart';

import 'splash_methods.dart';

class SplashView extends StatefulWidget {
  const SplashView({super.key});

  @override
  State<SplashView> createState() => _SplashViewState();
}

class _SplashViewState extends State<SplashView> {
  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    await SplashMethods.xieYi().then((value) {
      AppConfig.xieYIData = value;
    });
    SplashMethods.appInit().then((value) {
      AppConfig.appInitData = value;
      agreementDialog();
    }).catchError((err) {
      SmartDialog.showToast(err.message);
    });
  }

  void agreementDialog() async {
    if (sharedUtils.agreement) {
      pushPage();
      return;
    }
    final res = await Get.dialog(const XieYiWidget(), barrierDismissible: false);
    if (res == null || !res) {
      final res2 = await Get.dialog(const DisagreeDialogWidget(), barrierDismissible: false);
      if (res2 != null && res2) {
        agreementDialog();
      } else {
        Get.toNamed(PageRouter.home, parameters: {"test": "true"})?.then((value) {
          agreementDialog();
        });
      }
    } else {
      pushPage();
    }
  }

  void pushPage() async {
    Future.delayed(const Duration(seconds: 1), () {
      final token = sharedUtils.token;
      Get.offAllNamed(token.isEmpty ? PageRouter.login : PageRouter.index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Column(
          children: [
            const SizedBox(height: 200),
            ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.asset(
                AppConfig.appLogo,
                width: 80,
                height: 80,
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              AppConfig.appName,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0XFF333333)),
            ),
          ],
        ),
      ),
    );
  }
}
